<template>
    <div class="table-header">
        <el-button type="primary" @click="showAdd">添加</el-button>
        <div class="table-actions">
            <el-button :icon="Refresh" @click="refresh" />
            <!-- 列选择器弹窗 -->
            <el-popover v-model:visible="showColumnSelector" placement="bottom" width="200" trigger="click">
                <template #reference>
                    <el-button :icon="Operation" />
                    <!-- <el-button
            type="primary"
            size="small"
            @click="showColumnSelector = !showColumnSelector"
            icon="CirclePlus"
          >
            选择列
          </el-button> -->
                </template>
                <div class="column-selector">
                    <h3>选择显示列</h3>
                    <el-checkbox-group v-model="selectedColumns" @change="handleColumnChange">
                        <el-checkbox v-for="column in allColumns" :key="column.prop" :label="column.prop">
                            {{ column.label }}
                        </el-checkbox>
                    </el-checkbox-group>
                    <div class="selector-actions">
                        <el-button size="mini" @click="selectAll"> 全选 </el-button>
                        <el-button size="mini" @click="deselectAll"> 全不选 </el-button>
                    </div>
                </div>
            </el-popover>
        </div>
    </div>
    <el-table :data="tableData" border style="width: 100%">
        <!-- 动态渲染选中的列 -->
        <el-table-column v-for="column in filteredColumns" :key="column.prop" :prop="column.prop" :label="column.label"
            :width="column.width || 'auto'" :align="column.align || 'left'">
            <template #default="scope">
                <div v-if="column.prop === 'action'">
                    <el-button type="primary" size="small" @click="showDetil(scope.row)">详情</el-button>
                    <el-button type="primary" size="small" @click="editDetil(scope.row)">编辑</el-button>
                    <el-popconfirm class="box-item" @confirm="deleteItem(scope.row)" title="是否确认删除？" placement="top">
                        <template #reference>
                            <el-button type="danger" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                </div>
            </template>
        </el-table-column>
    </el-table>

    <!-- <div class="pagination">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[10, 20, 50]" :page-size="pageSize" layout="->,total, sizes, prev, pager, next, jumper"
      :total="121" />
  </div> -->
    <Detil ref="detilRef" />
    <AddOrEdit ref="addOrEditRef" :options="addOrEditOptions" @onSubmit="getList" />
</template>

<script setup>
import { ref, reactive, computed, defineExpose } from 'vue'
import Detil from '../components/Detil.vue'
import AddOrEdit from '../components/AddOrEdit.vue'
import * as ticketManagementApi from '@/api/ticketManagement/index'
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Refresh,
    Operation,
    Expand,
    Plus
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const detilRef = ref(null)
const addOrEditRef = ref(null)
const addOrEditOptions = ref({
    title: '', // 编辑以及添加的弹窗标题
    type: '' // 编辑以及添加的弹窗类型 控制事件
})
onMounted(() => {
    getList()
})
const getList = (data) => {
    const formData = data ? JSON.parse(JSON.stringify(data)) : {}
    formData.status = 2
    ticketManagementApi.getWorkorder(formData).then((res) => {
        tableData.value = res
    })
}
// 刷新
const refresh = () => {
    getList()
    ElMessage.success('刷新成功')
}
const onSubmit = () => {
    getList()
}
// 列选择器显示状态
const showColumnSelector = ref(false)
// 定义所有可用列
const allColumns = ref([
    { prop: 'id', label: '工单编号', width: 190, align: 'center' },
    { prop: 'follower', label: '跟单员', width: 120, align: 'center' },
    { prop: 'customerName', label: '客户名称', width: 120, align: 'center' },
    { prop: 'customerPhone', label: '客户手机号', width: 120, align: 'center' },
    { prop: 'sourceDate', label: '来源日期', width: 120, align: 'center' },
    { prop: 'platform', label: '平台', width: 120, align: 'center' },
    { prop: 'source', label: '来源', align: 'center' },
    { prop: 'enterpriseNo', label: '企业号', width: 150, align: 'center' },
    { prop: 'status', label: '工单状态', width: 120, align: 'center' },
    { prop: 'action', label: '操作', width: 220, align: 'center' }
])
// 表格数据（模拟）
const tableData = ref([])
// 选中的列 (初始选择所有列)
const selectedColumns = ref(allColumns.value.map((col) => col.prop))
// 过滤出选中的列
const filteredColumns = computed(() => {
    return allColumns.value.filter((col) => selectedColumns.value.includes(col.prop))
})
// 处理列选择变化
const handleColumnChange = (values) => {
    // 至少保留一列
    if (values.length === 0) {
        selectedColumns.value = [allColumns.value[0].prop]
    }
    // 这里可以添加保存到本地存储的逻辑
    localStorage.setItem('tableColumns', JSON.stringify(selectedColumns.value))
}

// 全选
const selectAll = () => {
    selectedColumns.value = allColumns.value.map((col) => col.prop)
    handleColumnChange(selectedColumns.value)
}

// 全不选
const deselectAll = () => {
    selectedColumns.value = []
    handleColumnChange(selectedColumns.value)
}
// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)

// 打开详情
const showDetil = (row) => {
    ticketManagementApi.detilWorkorder(row.id).then((res) => {
        detilRef.value.onOpen(res)
    })
}
// 打开添加弹窗
const showAdd = (row) => {
    addOrEditOptions.value = {
        type: 'add',
        title: '添加工单'
    }
    addOrEditRef.value.onOpen(row)
}
// 打开编辑弹窗
const editDetil = (row) => {
    addOrEditOptions.value = {
        type: 'edit',
        title: '编辑工单'
    }
    ticketManagementApi.detilWorkorder(row.id).then((res) => {
        addOrEditRef.value.onOpen(JSON.parse(JSON.stringify(res)))
    })
}
// 删除
const deleteItem = (row) => {
    ticketManagementApi.delWorkorder(row.id).then(() => {
        ElMessage({
            message: '删除成功',
            type: 'success'
        })
        getList()
    })
}
const handleSizeChange = (val) => {
    pageSize.value = val
}

const handleCurrentChange = (val) => {
    currentPage.value = val
}

defineExpose({
    getList
})
</script>
<style scoped lang="scss">
.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.table-actions {
    display: flex;
}

.pagination {
    margin-top: 15px;
    text-align: right;
}
</style>
